package com.mind.ridge.service.backend.impl;

import com.mind.ridge.service.backend.CommonService;
import com.mind.ridge.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author Mind
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Value("${ridge.dish-pic-path}")
    private String destPath;

    @Override
    public R<String> upload(MultipartFile file) {
        log.info(destPath);
        if (file == null) {
            return R.error("文件丢失，请重试");
        }
        //获取原始文件名，并截取其文件类型
        String originalFilename = file.getOriginalFilename();
        String fileType = "." + originalFilename.split("\\.")[1];
        //生成随机文件名，防止冲突
        String fileName = UUID.randomUUID() + fileType;

        //判断当前的文件夹是否存在
        File dir = new File(destPath);
        if (!dir.exists()) {
            //不存在则创建
            if (!dir.mkdirs()) {
                //若创建失败，则将位置换为C盘
                char disk = destPath.charAt(0);
                destPath = destPath.replace(disk, 'C');
                dir = new File(destPath);
                dir.mkdirs();
            }
        }
        try {
            file.transferTo(new File(destPath + fileName));
        } catch (IOException e) {
            return R.error("未知错误，文件上传失败！");
        }
        return R.success(fileName);
    }

    @Override
    public void download(String fileName, HttpServletResponse response) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            //创建输入流将文件写入
            fis = new FileInputStream(destPath + fileName);

            //获取输出流将图片写入浏览器
            response.setContentType("image/jpeg");
            os = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes,0,len);
                os.flush();
            }

        } catch (IOException e) {
            log.info(e.getMessage());
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
